package com.mystore.author.security.filter;

import com.mystore.author.security.utils.UrlUtils;
import com.mystore.common.consts.ApplicationConst;
import com.mystore.framework.pojo.Role;
import com.mystore.framework.pojo.Uri;
import com.mystore.framework.service.impl.IRoleServiceImpl;
import com.mystore.framework.service.impl.IUriServiceImpl;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class SecurityFilter implements FilterInvocationSecurityMetadataSource {
    @Resource
    private IUriServiceImpl iUriServiceImpl;
    @Resource
    private IRoleServiceImpl iRoleServiceImpl;
    AntPathMatcher antPathMatcher = new AntPathMatcher();//路径匹配的工具类，由于时间关系没自己写，源类有bug（相对于MyStore）
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        System.err.println("开始过滤");
        String requestUrl = ((FilterInvocation) o).getRequestUrl(); //获取用户的访问路径
        System.err.println(requestUrl);
        if(antPathMatcher.match("/console/user/**",requestUrl))
            return SecurityConfig.createList("NEED_LOGIN");
        AtomicBoolean atomicBoolean=new AtomicBoolean();//原子Boolean
        //判断是否不需要拦截
        Arrays.stream(ApplicationConst.GUEST_URIS).forEach(uri->{if(antPathMatcher.match(uri,requestUrl))atomicBoolean.set(true);});
        if(atomicBoolean.get())
            return SecurityConfig.createList("NOT_NEED_ROLE");
        //非过滤地址则处理，分析Role与Uri对比出有访问该地址的权限的角色
        List<Role> roles=iRoleServiceImpl.selectAll();
        List<Uri> uris = iUriServiceImpl.selectAll();//查询所有Uri
        for (Uri uri : uris) {
            if (antPathMatcher.match(uri.getUriLocation(),requestUrl)){ //比较Uri路径和请求路径是否一致
                List<Role> myRole = UrlUtils.getRoleList(String.valueOf(uri.getUriId()),roles);//如果匹配到了，拿到该路径对应的角色
                String[] str = new String[myRole.size()];
                for (int i = 0;i<myRole.size();i++) {
                    str[i] = myRole.get(i).getRoleId().toString();//将角色名赋值给str
                }
                return SecurityConfig.createList(str);//创建角色属性列表
            }
        }
        //end
        //如果没匹配到，则需要登录（可能是刚加的Uri但没有角色可以访问它）
        return SecurityConfig.createList("NOT_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
